'use strict';

const { Service } = require('egg');
const uuidv1 = require('uuid/v1');
const { Base64 } = require('js-base64');
const jwt = require('jsonwebtoken');

class UserService extends Service {
  async getUserList() {
    const { ctx, app } = this;
    const db = app.mysql.get('spring');
    let result = await db.select('t_user', {
      columns: [ 'id', 'register_time', 'role_id', 'username', 'user_id', 'status' ],
    });
    result = ctx.camelcaseKeys(result);
    return result;
  }

  async createUser(user) {
    const { app } = this;
    const db = app.mysql.get('spring');
    const { username, password, roleId } = user;
    const encodePassword = Base64.encode(password);
    const userId = uuidv1();
    const result = await db.insert('t_user', {
      username,
      password: encodePassword,
      role_id: roleId,
      user_id: userId,
    });
    return result;
  }

  async getUser(user) {
    const { app } = this;
    const db = app.mysql.get('spring');
    const { username, password } = user;
    const encodePassword = Base64.encode(password);
    const existUser = await db.get('t_user', {
      username,
      password: encodePassword,
    });
    if (!existUser) {
      return null;
    }
    return existUser;
  }

  async getUserByUserId(userId) {
    const { ctx, app } = this;
    const db = app.mysql.get('spring');
    const existUser = await db.select('t_user', {
      where: {
        user_id: userId,
      },
      columns: [ 'username', 'user_id' ],
    });
    if (!existUser || existUser.length === 0) {
      return null;
    }
    const result = ctx.camelcaseKeys(existUser[0]);
    return result;
  }

  async login(user) {
    const { app } = this;
    const db = app.mysql.get('spring');
    const { username, password } = user;
    const encodePassword = Base64.encode(password);
    const existUser = await db.get('t_user', {
      username,
      password: encodePassword,
    });

    if (!existUser) {
      return null;
    }

    // 验证通过
    const token = jwt.sign({ userId: existUser.user_id }, app.config.jwtSecret, { expiresIn: '7d' });
    return token;
  }
}

module.exports = UserService;
